import { useStorage } from '@/utils/storage';
import { ref } from 'vue';
import { $EventName } from '@/utils/const/env';
export default () => {
    const storage = useStorage()
    const WebConfigStorageKey = 'WEBCONFIG'
    const WEBCONFIG = ref<WebConfigInterface>();
    const setWebConfig = (WebConfig: WebConfigInterface): Promise<boolean | string> => {
        WEBCONFIG.value = WebConfig;
        uni.$emit($EventName.WEBCONFIG_READY, WebConfig);
        // #ifdef H5
        const __uniConfigTypeof = typeof globalThis.__uniConfig !== undefined;
        if(__uniConfigTypeof){
            if (WebConfig.amap_web_key) {
                globalThis.__uniConfig.aMapKey = WebConfig.amap_web_key;
            }
            if (WebConfig.amap_service_host) {
                globalThis.__uniConfig.aMapServiceHost = WebConfig.amap_service_host;
            }
            if (WebConfig.amap_js_code) {
                globalThis.__uniConfig.aMapSecurityJsCode = WebConfig.amap_js_code;
            }

        }
        // #endif
        return storage.set(WebConfigStorageKey, WebConfig);
    }
    const initWebConfig = (): void => {
        const webconfig = storage.get(WebConfigStorageKey)
        if (webconfig !== null) {
            setWebConfig(webconfig as WebConfigInterface);
        }
    }
    const clearWebConfig = (): Promise<boolean> => {
        WEBCONFIG.value = undefined;
        return storage.remove(WebConfigStorageKey)
    }
    const hasPermission = (permission: string | string[]): boolean => {
        if (!WEBCONFIG.value) {
            return false;
        }
        if (Array.isArray(permission)) {
            return permission.every(item => !!WEBCONFIG.value[item]);
        }
        return !!WEBCONFIG.value[permission];
    }
    const replaceIndustryPersonnelName = (s: string) => {
        if (!WEBCONFIG.value || !s || !s.includes('技师')) {
            return s;
        }
        return s.replace('技师', WEBCONFIG.value?.industry_personnel_name);
    }
    return {
        WEBCONFIG,
        setWebConfig,
        initWebConfig,
        clearWebConfig,
        hasPermission,
        replaceIndustryPersonnelName
    };
}